import type { InvokeArgs } from "@tauri-apps/api/tauri";
import type { EventName, EventCallback } from "@tauri-apps/api/event";
import type { OpenDialogOptions } from "@tauri-apps/api/dialog";
const app = await import("@tauri-apps/api");
export const appInvoke = async <T>(
  cmd: string,
  args?: InvokeArgs
): Promise<T> => {
  console.log(cmd, args);
  if (!Tauri.isTauri()) return null as T;
  const { invoke } = await import("@tauri-apps/api");
  return invoke(cmd, args);
};
export const appListen = async <T>(
  name: EventName,
  handler: EventCallback<T>
) => {
  if (!Tauri.isTauri()) return null;
  const { listen } = await import("@tauri-apps/api/event");
  return listen(name, handler);
};
export const Tauri = {
  isTauri: () => {
    return Boolean(
      typeof window !== "undefined" &&
        window !== undefined &&
        window.__TAURI_IPC__ !== undefined
    );
  },
  createWindow: async ({
    label,
    title,
    url,
    width,
    height,
  }: {
    label: string;
    title: string;
    url: string;
    width: number;
    height: number;
  }) => {
    appInvoke("create_window", { width, height, title, url, label });
  },
  getFreePort: (): Promise<number> => {
    return appInvoke("get_free_port", { min: 10000, max: 20000 });
  },
  gptVitsStart: async (
    port: number,
    config: GptSoVitsConfig,
    handler: (result: any) => void
  ) => {
    appInvoke("run_cmd", {
      command: `cd plugins\\GPT-SoVITS && runtime\\python.exe api.py ${concatenateKeyValue(
        { ...config, "-p": port }
      )}`,
    });
    const listen = await appListen("cmd_output", (e: any) => {
      console.log(e.payload.message);
      handler(e);
    });
    return listen;
  },
  comfyStart: async (handler?: (result: any) => void) => {
    const id = await appInvoke("run_cmd", {
      command: `cd plugins\\ComfyUI_windows_portable && .\\python_embeded\\python.exe -s ComfyUI\\main.py`,
    });
    const listen = await appListen("cmd_output", (e: any) => {
      console.log(e.payload.message);
      handler?.(e);
    });
    return { listen, id };
  },
  dialogOpen: async (config: OpenDialogOptions) => {
    try {
      const { dialog } = await import("@tauri-apps/api");
      const result = await dialog.open(config);
      return result;
    } catch (error) {
      return error as Error;
    }
  },
  showWindow: async (label: string) => {
    const windows = new app.window.WindowManager(label);
    windows.show();
    windows.setFocus();
  },
  readFilesContents: (filePaths: string[]): Promise<string[]> => {
    return appInvoke("read_files_contents", { filePaths }) ?? [];
  },
  getFilesPath: (rootPath: string): Promise<string[]> => {
    return appInvoke("get_files_path", { rootPath });
  },
};
